import { FormModal } from "@/components/modal/form.modal"
import { Field_Search } from "@/components/utils/field.list"
import stocksService from "@/services/stocks.service"
import { StoreContext } from "@/store"
import { AsyncModal, OperateRender, IndexRender, FormRender, ListTable, DateRender } from "@whzhuke/antd"
import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Modal, Row, Space } from "antd"
import { useForm } from "antd/es/form/Form"
import React, { useCallback, useContext, useState, useEffect } from "react"
import { EditStocks } from "@/components/form/stocks/edit.stocks"
import goodsService from "@/services/goods.service"
import { functionCommon } from "@whzhuke/common"

// 单位映射：套=1, 件=2, 个=3, 台=4
const unitMap: Record<string, number> = {
  套: 1,
  件: 2,
  个: 3,
  台: 4
}

const Page = useMobx(() => {
  const [form] = useForm()
  const { ListStore } = useContext(StoreContext)
  const [unitDisplayMap, setUnitDisplayMap] = useState<Record<number, string>>({})

  // 获取单位列表
  useEffect(() => {
    goodsService
      .unitslist({})
      .then(res => {
        const map: Record<number, string> = {}
        res.data?.forEach((item: { value: string; key: string }) => {
          const numValue = unitMap[item.value]
          if (numValue) {
            map[numValue] = item.key
          }
        })
        setUnitDisplayMap(map)
      })
      .catch(err => {
        console.error("获取单位列表失败:", err)
      })
  }, [])

  const countRender = useCallback(
    (_: unknown, { count, unit }: { count?: number; unit?: number }) => (count == null ? "-" : `${count} ${unitDisplayMap[unit!] || "-"}`),
    [unitDisplayMap]
  )

  const declareStatusRender = useCallback((val?: boolean | string | null) => {
    if (val === true || val === "true") return "已申报"
    if (val === false || val === "false") return "未申报"
    return val || "-"
  }, [])

  const Zanwu = useCallback(async () => {}, [])
  const titleRender = useCallback(
    () => (
      <Row justify="space-between" align="middle">
        <Col />
        <Col>
          <Space size="middle">
            <Button type="primary" onClick={Zanwu}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>
    ),
    []
  )

  const onFinish = useCallback(data => {
    const [start, end] = data.range || []
    data.startTime = start ? new Date(start).getTime() : undefined
    data.endTime = end ? new Date(end).getTime() : undefined
    delete data.range
    ListStore.setParams(stocksService.list, data)
  }, [])

  const DeclareModal = useCallback(
    (val?, item?) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formEle: EditStocks,
          formProps: {
            values: item,
            service: stocksService
          },
          title: "库存申报"
        }
      })
      if (done) {
        ListStore.updateList(stocksService.list)
      }
    },
    []
  )

  const previewContract = useCallback((fileUrl?: string) => {
    if (!fileUrl) {
      Modal.warning({ title: "提示", content: "暂无可预览的合同文件" })
      return
    }

    const viewerOrigin = window.location.origin
    const previewBase = `${viewerOrigin}/web/viewer.html?file=`
    const normalizedUrl = functionCommon.requestHost("public") + fileUrl
    const previewUrl = `${previewBase}${encodeURIComponent(normalizedUrl)}`
    window.open(previewUrl, "_blank")
  }, [])

  const renderFileUrl = useCallback(
    (_: string, item: any) => {
      const rawUrl = item?.fileUrl
      if (!rawUrl) return "-"

      const extTarget = rawUrl.split("?")[0]?.toLowerCase() || ""
      const isPdf = extTarget.endsWith(".pdf")

      if (isPdf) {
        return (
          <Button type="link" onClick={() => previewContract(rawUrl)}>
            预览
          </Button>
        )
      }

      const downloadUrl = `${functionCommon.requestHost("public")}${rawUrl}`
      return downloadUrl ? (
        <a href={downloadUrl} target="_blank" rel="noopener noreferrer">
          下载
        </a>
      ) : (
        "-"
      )
    },
    [previewContract]
  )
  return (
    <Row>
      <Col span={24}>
        <FormRender
          form={form}
          onFinish={onFinish}
          layout="inline"
          fieldList={[
            {
              fieldType: "rangeDate",
              formItemConfig: {
                name: "range",
                label: "提交时间"
              },
              config: {
                showTime: !0,
                format: "YYYY-MM-DD HH:mm:ss"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同编号",
                name: "code"
              },
              config: {
                placeholder: "合同编号"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同名称",
                name: "name"
              },
              config: {
                placeholder: "合同名称"
              }
            },

            Field_Search
          ]}
        />
      </Col>
      <Col span={24}>
        <ListTable
          title={titleRender}
          apiColumns={[
            IndexRender("id", 80),
            ["code", "合同编号"],
            ["name", "合同名称"],
            ["fileUrl", "合同地址", renderFileUrl],
            ["declareStatus", "订单进度", declareStatusRender],
            ["count", "申报数量", countRender],
            ["declareBy", "提交人"],
            ["declareTs", "提交时间", DateRender()],
            ["id", "操作", OperateRender([["申报", DeclareModal]]), { width: 80, fixed: "right" }]
          ]}
          apiService={stocksService.list}
          // testData={stockTestData}
        />
      </Col>
    </Row>
  )
})

export default Page
